import { Injectable } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import { RedisInstance } from '../../../../../util/redis';
import { UserService } from '../user/user.service';
import { v4 as uuidv4 } from 'uuid';
import * as QRCode from 'qrcode';

@Injectable()
export class AuthService {
  constructor(private readonly userService: UserService) {}
  async login(body: any) {
    const userInfo = await this.userService.findUserByName(body.username);
    if (userInfo.length === 0) {
      return { code: 200, flag: false, msg: '用户名不存在' };
    }
    if (userInfo.length > 1) {
      return { code: 200, flag: false, msg: '用户名重复' };
    }
    if (body.password != userInfo[0].password) {
      return { code: 200, flag: false, msg: '密码错误' };
    }
    return { code: 200, flag: true, msg: '匹配成功', data: userInfo[0] };
  }

  async generateGraphicCode(ip) {
    const captcha = svgCaptcha.create({
      size: 6, //验证码长度
      fontSize: 50,
      width: 110,
      height: 38,
      background: '#cc9966', //背景颜色
    });
    await RedisInstance.initRedis('auth.captchaImage', 2);
    const key = uuidv4() + '-' + ip;
    await RedisInstance.setRedis('auth.login', 2, key, `${captcha.text}`, 300);
    return {
      codeId: key,
      codeSvg: captcha.data,
    };
  }

  async generateQRCode(ip: string, query: { jumpPath: string }) {
    const codeInfo = query.jumpPath + Math.floor(Date.now() / 1000) + '/' + ip;
    const qrData = await QRCode.toDataURL(codeInfo, {
      errorCorrectionLevel: 'H',
      type: 'image/png',
      width: 200,
      margin: 0,
      color: {
        dark: '#000000',
      },
    });
    return {
      code: 200,
      data: qrData,
      msg: 'ok',
    };
  }
}
